package com.example.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.example.entity.Order;
import com.example.entity.ResponseResult;
import com.example.entity.RestResultGenerator;
import com.example.exception.GoodsStockException;
import com.example.factory.OrderFactory;
import com.example.service.OrderService;

@Controller
@RequestMapping(value = "order")
public class OrderController {

	@Autowired
	private OrderService orderService;

	@RequestMapping(value = "create", method = RequestMethod.GET)
	@ResponseBody
	public ResponseResult<Order> create(Order order) {
		order = OrderFactory.getOrderFactory().getOrder()
				.setBuyGoodsNum(5L)
				.setUserName("张三");
		ResponseResult<Order> result;
		try {
			orderService.create(order);
		} catch (GoodsStockException e) {
			result = RestResultGenerator.result(order, false, "库存不足");
		} catch (Exception e1) {
			result = RestResultGenerator.result(order, false, e1.getMessage());
		}
		result = RestResultGenerator.result(order, true, "创建成功");
		return result;
	}

	@RequestMapping(value = "query/{id}", method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<Order> queryUserById(@PathVariable("id") Long id) {
		try {
			Order order = orderService.selectById(id);
			if (null == order) {
				// 资源不存在，响应404
				return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
			} else {
				// 200
				return ResponseEntity.ok(order);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 500
		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
	}
}
